﻿using System.IO;
using System.Web.Mvc;

namespace StudyEnglish.Models
{
    /// <summary>
    /// Action result for download files
    /// </summary>
    public class DownloadFileResult : ActionResult
    {
        /// <summary>
        /// File Path
        /// </summary>
        private readonly string FilePath;

        /// <summary>
        /// File Name
        /// </summary>
        private readonly string FileName;

        /// <summary>
        /// FileType
        /// </summary>
        private readonly string FileType;

        public DownloadFileResult(string filepath, string filename)
        {
            FilePath = filepath;
            FileName = filename;
            FileType = "application/octet-stream";
        }

        public DownloadFileResult(string filepath, string filename, string filetype)
        {
            FilePath = filepath;
            FileName = filename;
            FileType = filetype;
        }



        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            if (File.Exists(FilePath))
            {
                response.Clear();
                response.ContentType = FileType;
                response.AppendHeader("Content-disposition", string.Format("attachment; filename=\"{0}\"", FileName));
                response.Flush();
                response.WriteFile(FilePath);
            }
            else
            {
                throw new FileNotFoundException(FilePath);
            }
        }
    }
}